<template>
  <div id="goods">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-button type="primary" @click="addCation">添加分类</el-button>
      </div>
      <!-- 添加分类对话框 -->
      <el-dialog
        title="添加商品分类"
        :visible.sync="addVisible"
        width="50%"
        @close="downAll"
      >
        <!-- 表单 -->
        <el-form
          :rules="addRules"
          ref="allAddRef"
          :model="addForm"
          label-width="82px"
        >
          <el-form-item label="分类名称:" prop="cat_name">
            <el-input v-model="addForm.cat_name"></el-input>
          </el-form-item>
          <el-form-item label="父级分类:">
            <!-- options用来指定数据源 -->
            <!-- props用来指定配置对象 -->
            <div class="block">
              <el-cascader
                v-model="parentIdKeys"
                :options="pargetUser"
                :props="caseProps"
                @change="parentChange"
                clearable
                change-on-select
              >
              </el-cascader>
            </div>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addVisible = false">取 消</el-button>
          <el-button type="primary" @click="addCat">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 表格 -->
      <tree-table
        :data="getAllGoods"
        :columns="columns"
        show-index
        index-text="#"
        border
        :expand-type="false"
        :selection-type="false"
      >
        <template slot-scope="scope" slot="isOk">
          <i
            class="el-icon-success"
            style="color: #39ce39"
            v-if="scope.row.cat_deleted === false"
          ></i>
          <i class="el-icon-error" style="color: #f56c6c" v-else></i>
        </template>
        <template slot-scope="scope" slot="level">
          <el-tag
            class="el_tag"
            size="mini"
            effect="dark"
            v-if="scope.row.cat_level == 0"
            >一级</el-tag
          >
          <el-tag
            class="el_tag"
            size="mini"
            type="success"
            effect="dark"
            v-else-if="scope.row.cat_level == 1"
            >二级</el-tag
          >
          <el-tag class="el_tag" size="mini" type="warning" effect="dark" v-else
            >三级</el-tag
          >
        </template>
        <template slot-scope="scope" slot="operation">
          <el-button
            type="primary"
            icon="el-icon-edit"
            class="editor"
            @click="btnEditor(scope.row.cat_id)"
            ><span>编辑</span></el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            class="delete"
            @click="btnDel(scope.row.cat_id)"
            ><span>删除</span></el-button
          >
        </template>
      </tree-table>
      <!-- 编辑弹出框 -->
      <el-dialog
        title="修改分类名称"
        :visible.sync="editorsVisible"
        width="50%"
        @close="downEditor"
      >
        <el-form
          :rules="editorRules"
          ref="editorRef"
          :model="editorForm"
          label-width="82px"
        >
          <el-form-item label="分类名称:" prop="cat_name">
            <el-input v-model="editorForm.cat_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editorsVisible = false">取 消</el-button>
          <el-button type="primary" @click="editorInfo">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分页区域 -->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="questInfo.pagenum"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="5"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'categories',
  data() {
    return {
      // 商品数据列表
      getAllGoods: [],
      // 商品分页
      questInfo: {
        type: '3',
        pagenum: 1,
        pagesize: 5,
      },
      // 总数据
      total: 0,
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name',
        },
        {
          label: '是否有效',
          type: 'template',
          template: 'isOk',
        },
        {
          label: '排序',
          type: 'template',
          template: 'level',
        },
        {
          label: '操作',
          type: 'template',
          template: 'operation',
        },
      ],
      // 添加分类
      addVisible: false,
      // 添加分类的表单数据
      addForm: {
        cat_name: '',
        cat_pid: 0,
        cat_level: 0,
      },
      // 添加分类表单验证
      addRules: {
        cat_name: [
          { required: true, message: '分类名称不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 8,
            message: '分类名称长度在1~8个字符',
            trigger: 'blur',
          },
        ],
      },
      // 父级分类数据
      pargetUser: [],
      // 配置对象
      caseProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      // 被选中的id数组值
      parentIdKeys: [],
      // 编辑弹出框
      editorsVisible: false,
      // 编辑数据
      editorForm: {
        cat_name: '',
      },
      editorRules: {
        cat_name: [
          { required: true, message: '分类名称不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 8,
            message: '分类名称长度在1~8个字符',
            trigger: 'blur',
          },
        ],
      },
    }
  },
  created() {
    // 商品分类列表
    this.getGoods()
  },
  methods: {
    // 商品分类总数据
    async getGoods() {
      const { data: res } = await this.$http.get('categories', {
        params: this.questInfo,
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.getAllGoods = res.data.result
      this.total = res.data.total
    },
    handleSizeChange(newPageSize) {
      this.questInfo.pagesize = newPageSize
      this.getGoods()
    },
    handleCurrentChange(newPageNum) {
      this.questInfo.pagenum = newPageNum
      this.getGoods()
    },
    // 点击添加分类
    addCation() {
      this.getParentUser()
      this.addVisible = true
    },
    async getParentUser() {
      const { data: res } = await this.$http.get('categories', {
        params: {
          type: 2,
        },
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.pargetUser = res.data
      // console.log(this.pargetUser)
    },
    // 选中后改变值
    parentChange() {
      // 如果parentIdKeys的数组长度大于0，就说明选中了父级分类
      // 反之就没有
      if (this.parentIdKeys.length > 0) {
        this.addForm.cat_pid = this.parentIdKeys[this.parentIdKeys.length - 1]
        // 为当前分类的等级赋值
        this.addForm.cat_level = this.parentIdKeys.length
      } else {
        // 父级分类的id
        this.addForm.cat_pid = 0
        // 为当前分类的等级赋值
        this.addForm.cat_level = 0
      }
    },
    // 点击确定添加按钮
    addCat() {
      this.$refs.allAddRef.validate(async (vail) => {
        if (vail == false) return this.$message.error('表单验证失败')
        const { data: res } = await this.$http.post('categories', this.addForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success('添加成功')
        this.getGoods()
        this.addVisible = false
        console.log(res)
      })
    },
    // 关闭添加对话框
    downAll() {
      this.$refs.allAddRef.resetFields()
      this.parentIdKeys = []
      this.addForm.cat_pid = 0
      this.addForm.cat_level = 0
    },
    // 点击编辑
    async btnEditor(id) {
      const { data: res } = await this.$http.get(`categories/${id}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editorForm = res.data
      this.editorsVisible = true
    },
    // 确定提交编辑
    editorInfo() {
      this.$refs.editorRef.validate(async (vail) => {
        if (!vail) return this.$message.error('表单验证失败')
        const { data: res } = await this.$http.put(
          `categories/${this.editorForm.cat_id}`,
          this.editorForm
        )
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.getGoods()
        this.editorsVisible = false
      })
    },
    // 关闭编辑弹出框
    downEditor() {
      this.$refs.editorRef.resetFields()
    },
    // 删除按钮
    btnDel(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async() => {
          const {data:res} = await this.$http.delete(`categories/${id}`)
          if(res.meta.status !== 200) return this.$message.error(res,meta.msg)
          this.getGoods();
          this.$message.success('删除成功')
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
  },
}
</script>

<style lang="less" scoped>
.box-card {
  width: 100% !important;
  margin-top: 15px;
  box-shadow: none !important;
}
/deep/ .el-card__header {
  padding: 20px;
  border-bottom: none;
}
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: '';
}
.clearfix:after {
  clear: both;
}

.box-card {
  width: 480px;
}
.editor,
.delete {
  padding: 7px 15px;
  font-size: 12px;
}
.el-pagination {
  margin-top: 15px;
}
.el-cascader {
  width: 100%;
}
</style>